<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
    public function index(){
		//实例化数据表模型
		$model = M('area');
		//查询省份/直辖市信息
		$province = $model -> where(array('parent_id' => 1)) -> select();
		//传递数据给模版展示
		//dump($province);die;
		$class = new \Org\Net\IpLocation('qqwry.dat');
		$data = $class ->getlocation('121.237.3.191');
		$data = $data['country'];
		//echo $data;
		$data = iconv("GB2312","UTF-8",$data);

		//展示广告主页
		$fb = M('fb');
        $count = $fb->count();
        $page = new \Think\Page($count,6);
        $page -> setConfig('prev','上一页');
        $page -> setConfig('next','下一页');
        $page -> setConfig('first','首页');
        $page -> setConfig('last','末页');
        //$page -> lastSuffix = false;    //
        $pageList = $page ->show();
        $info = $fb ->order('id desc')->limit($page->firstRow.",".$page ->listRows)->select();
        $this->assign('pagelist' , $pageList);  
        $this->assign('info' , $info);  
	    $this->assign('data' , $data);	
		$this -> assign('province',$province);
		$this -> display();
	}

    protected function ajaxReturn($data, $type = '', $json_option = 0)
    {
        parent::ajaxReturn($data, $type, $json_option); // TODO: Change the autogenerated stub
    }

    //处理ajax发来的各种数据
    public  function doAjax()
    {
        //echo 11;die;
        //获取jquery得到的信息
        #从数据库搜索资金若大于填写的才让其发布广告
        $user = M('user');
        $id = session('id');
        $money = $user ->field('money')->find("$id");
        //一维数组注意数据的获取
        $money = $money['money'];
        //echo $money;
        $yusuan = I('post.yusuan');
        //强制转换
        $money = (int)$money;
        //数据库里面金额发生变化
        $money = $money - $yusuan;
        $yusuan = (int)$yusuan;        
        if($money > $yusuan){
            //echo 11;die;
            $data['answer1'] = I('post.answer1');
            $data['answer2']= I('post.answer2');
            $data['answer3'] = I('post.answer3');
            $data['question'] = I('post.question');
            //dump(I('post.'));die;
            //$data['interest'] = implode(",",I('post.interest'));
            $data['province_id'] = I('post.province');
            $data['city_id'] = I('post.city');
            $data['district_id'] = I('post.district');
            //$data['price'] = I('post.price');
            $data['add_time'] = time();
            $answercorrect= I('post.answercorrect');
            $geshu = I('post.geshu');
            //$question = M('question');
            $fb = M('fb');
            //$fb->field('province,city,district')->add(array('province'=>$province,'city'=>$city,'district'=>$district));
            //echo $question;
            //dump($data);die;
            //$info1 = $question->field('question')->add(array($ques));
            //echo $answercorrect;
            //$num = $answer->field('answer1,answer2,answer3,question,add_time,province_id,city_id,district_id')->add($data);
            if($answercorrect === "answer1"){
                $data['isright'] = $data['answer1'];
                //$answer->field('isrignt')->save($data2);
                $num = $fb->field('answer1,answer2,answer3,question,isright,province_id,city_id,district_id,add_time')->add($data);
                //echo 11;
                //$answer-> where("id=75")->setField('isrignt','test');
                
            }
            if($answercorrect === "answer2"){
                //echo 22;
                $data['isright'] = $data['answer2`'];
                //$answer->field('isright')->save(array('answer2' =>$data['answer2']));
                $num = $fb->field('answer1,answer2,answer3,question,isright,province_id,city_id,district_id,add_time')->add($data);
                $answer-> where("id=".$num)->setField('isrignt','$data["answer2"]');
            }if($answercorrect === "answer3"){
                //echo 33;
                $data['isright'] = $data['answer3'];
                //$answer->field('isright')->save(array('answer3' =>$data['answer3']));
                $num = $fb->field('answer1,answer2,answer3,question,isright,province_id,city_id,district_id,add_time')->add($data);
                 //$answer-> where("id=".$num)->setField('isrignt','$data["answer3"]');
            }
            //echo $num;die;
            $data2['money'] = (string)$money;
            $user ->where("id={$id}") ->save($data2);
            $data3['bigHongbao'] = $yusuan;
            $data3['num'] = $geshu;
            $fb ->where("id=$num")->save($data3);
            $val = json_encode(array('status'=>"1","data" =>"$num"));
            echo $val;
            //完成重要的一步
        }else{
            //echo 22;die;
            //从数据库扣除相应的金额，并且写入数据库
            
            $val = json_encode(array("status" => "0" , "data" => "请充值"));

            echo $val;
            /*echo "<script type='text/javascript'>           
                    window.location.href='http://localhost/xgxad/index.php/Home/Index/fabu/';
                </script>";*/
        
        }
    }
    
    
    
    
    
    
    //空操作
     function _empty() //魔术方法？？
    {
        $this ->display('Empty/error');
    }

    public function getAreaByAreaId()
    {
        //接收地区id
        $pid = I('post.pid');
        //先实例化数据表模型
        $model = M('Area');
        $data = $model -> where(array('parent_id' => $pid)) -> select();
        //以json格式输出地区信息
        //echo json_encode($data);
        $this -> ajaxReturn($data);
    }



    public function fabu()
    {
        #实例化模型，表单提交数据
        
    	// header("location:http://localhost/xgxad/index.php/home/index/fabu2") ;
        	$model = M('area');
            //查询省份/直辖市信息
            $province = $model -> where(array('parent_id' => 1)) -> select();
            $this -> assign('province',$province);
        	$this ->display();
        
    	
    }

    //广告细节的处理
    public function detail()
    {
        $id = I('get.id');
        $fb = M('fb');
        //问题表包含了问题和答案等许多信息
        $answer = M('answer');
        $detail = $fb ->where("id=".$id)->find();
         //dump($detail);die;
        $this ->assign('detail' , $detail);

        $this->display();
    }

    public function redbag_record()
    {
      $id = I("get.id");
      $fb = M('fb');
      $hongbaos = $fb->find("$id");
      if($hongbaos['flag'] == 0){
          //查询出红包的一维数组转变成大字符串
          $hongbaos = $hongbaos['redbags'];
          //把字符串变成数组
          $hongbaos = explode(",", $hongbaos);
          //dump($hongbaos);die;
          //删掉一个数组元素，然后再次变为字符串进行保存
          $hongbao = array_shift($hongbaos);
          $hongbaos = implode(",",$hongbaos);
          $data['redbags'] = $hongbaos;
          $data['flag'] = '1';
          //dump($data);die;
          $fb->where("id=$id")->save($data);
          //把数据回显到页面 
          $this ->assign('hongbao' , $hongbao);
        }else{
          $this ->assign('hongbao' , "你已经抢过一次，请抢其他广告的红包");
        }
      $this->display();
    }

    public function dealfabu()
    {
        
       
        //dump($money);die;
            $model = M('fb');
            //$data = $model ->create();
            $num = I('post.num');
            $id = session('id');
            //echo $num;die;
             $interest = I('post.interest');
             $interest = implode("," ,$interest);
            //echo $interest;die;
            #实例化上传类
            $cfg = array(
                    'rootPath'      =>  WORKING_PATH . UPLOAD_ROOT_PATH //保存根路径
                );
            $upload = new \Think\Upload($cfg);
            #上传
            $info = $upload -> uploadOne($_FILES['pic']);
            //var_dump($info);die;
            #判断上传的结果，上传失败返回false
            if($info){
                $data = array(
                    'filepath' =>UPLOAD_ROOT_PATH.$info['savepath'].$info['savename'],
                    'filename' =>$info['savename'],
                    'hasfile' => 1,
                    "interest" =>$interest,
                    "uid"     => $id,
                    );
            }
            $rst = $model ->where("id={$num}")-> save($data);
            #判断添加操作返回值
            if($rst ){
                #添加成功
                    $this ->redBags($num);
                    $this -> success('添加成功~',U('index'),1);
                }else{
                    #添加失败
                    $this -> error('添加失败~',U('fabu'),1);
                }

        


        
    }



     //生成红包算法，实现设定好的红包
   public function redBags($a)
   {
      $total = 20;//红包总金额   
      $num = 10;// 分成10个红包，支持10人随机领取   
      $min = 0.01;//每个人最少能收到0.01元   
      $arr = [];
      for ($i = 1;$i < $num;$i++)   
      {   
      $safe_total = ($total-($num-$i)*$min)/($num-$i);//随机安全上限   
      $money = mt_rand($min*100,$safe_total*100)/100;   
      $total = $total-$money;  
      $arr[$i] = $money;  
      }  
      $arr[] = $total ;
      $arr = implode(",", $arr);
      //dump($arr);die;
      $fb = M('fb');
      $data['id'] = $a;
      $data['redbags'] = $arr;
      //把红包字符串插入数据库
      $fb ->save($data);
      //备份该红包生成的数据
      $data2['beifen'] = $arr;
      $data2['id'] = $a;
      $fb ->save($data2);
      
   }

    /*
   ** 发放红包
    */
    public function faHongbao()
    {
      $id = I("get.id");
      $fb = M('fb');
      $hongbaos = $fb->find("$id");
      //查询出红包的一维数组转变成大字符串
      $hongbaos = $hongbaos['redbags'];
      //把字符串变成数组
      $hongbaos = explode(",", $hongbaos);
      //dump($hongbaos);die;
      //删掉一个数组元素，然后再次变为字符串进行保存
      $hongbao = array_shift($hongbaos);
      $hongbaos = implode(",",$hongbaos);
      $data['redbags'] = $hongbaos;
      //dump($data);die;
      $fb->where("id=$id")->save($data);
      echo $hongbao;
      

    }


/*   private function deal_ad($goods_id){
        //判断有上传图片
        $ishave = false;
        foreach($_FILES['goods_pics']['error'] as $k => $v){
            //判断至少有一个上传，并且该相册是ok的
            if($v=== 0){
                $ishave = true;
            }
        }

        if($ishave === true){
            //有上传相册图片
            //dump($_FILES);
            //实现批量相册上传
            $cfg = array(
                'rootPath'      =>  WORKING_PATH . UPLOAD_ROOT_PATH , //保存根路径
            );
            $up = new \Think\Upload($cfg);
            //从$_FILES里边获得goods_pics的相册信息
            //upload($_FILES)
            $z = $up -> upload(array($_FILES['goods_pics']));
            //dump($z);

            //遍历$z,对各个上传好的"相册"进行对应的处理
            //要制作3幅缩略图
            $im = new \Think\Image();
            foreach($z as $k => $v){
                //原图路径名
                $yuan_path_name = $up->rootPath.$v['savepath'].$v['savename'];
                //给原图制作缩略图
                $im -> open($yuan_path_name);
                $im -> thumb(800,800,6);
                //保存制作好的缩略图
                $b_name = $up->rootPath.$v['savepath'].'b_'.$v['savename'];
                $im -> save($b_name);

                $im -> thumb(350,350,6);
                $m_name = $up->rootPath.$v['savepath'].'m_'.$v['savename'];
                $im -> save($m_name);

                $im -> thumb(50,50,6);
                $s_name = $up->rootPath.$v['savepath'].'s_'.$v['savename'];
                $im -> save($s_name);
                //存储3幅缩略图到数据库(sp_goods_pics)
                $arr = array(
                    'goods_id'=>$goods_id,
                    'goods_pics_b' => $b_name,
                    'goods_pics_m' => $m_name,
                    'goods_pics_s' => $s_name,
                );
                D('GoodsPics')->add($arr);
            }
        }
    }*/
    

    




   
































}